<template>
  <div>
    <a-card :bordered="false" :bodyStyle="{ padding: '16px', height: '100%' }">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="结算名称:">
                <a-input
                  v-model="keywords"
                  placeholder="请输入结算名称(回车搜索)"
                  @pressEnter="$refs.table.refresh(true)"
                  style="width: 80%"
                >
                  <a-tooltip slot="suffix" title="请输入结算名称">
                    <a-icon type="search" style="color: rgba(0, 0, 0, 0.45)" @click="$refs.table.refresh(true)" />
                  </a-tooltip>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="发薪日期:">
                <a-month-picker placeholder="请选择月份" @change="monthChange" style="width: 80%" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="结算状态:">
                <a-select v-model="queryParam.status" placeholder="请选择结算状态" style="width: 80%" allowClear>
                  <a-select-option :value="1"> 已确认 </a-select-option>
                  <a-select-option :value="2"> 未确认 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="btn-list">
        <a-button type="primary" class="mr10" @click="goAdd"> 新建一笔结算 </a-button>
        <a-button class="mr10" @click="goSet">设置员工工资</a-button>
        <a-button class="mr10" @click="openGZT">设置工资条项目</a-button>
      </div>
      <div>
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          showPagination="auto"
          class="user_management_table"
          :pagination="pagination"
        >
          <span slot="name" slot-scope="text, record">
            <a @click="goInfo(record.id)">{{ record.name }}</a>
          </span>
          <span slot="section" slot-scope="text, record"> {{ record.start_time }}至{{ record.end_time }} </span>
          <span slot="teacher_user" slot-scope="text, record">
            <span v-if="record.teacher_names.length < 3">
              <span v-for="(item, index) in record.teacher_names" :key="index">
                {{ item }} <span v-if="index != record.teacher_names.length - 1">，</span>
              </span>
            </span>
            <span v-else>
              {{ record.teacher_names[0] }}，{{ record.teacher_names[1] }}等{{ record.teacher_names.length }}人
            </span>
          </span>
          <span slot="money" slot-scope="text, record"> ￥{{ record.money }} </span>
          <span slot="status" slot-scope="text, record">
            <span>{{ record.status&&record.status==1?'已确认':'未确认' }}</span>
          </span>
          <span slot="action" slot-scope="text, record">
            <a @click="exportItem(record.id)">导出</a>
            <span style="color: rgb(191, 191, 191); margin: 0px 4px">|</span>
            <a @click="deleteItem(record.id)">删除</a>
          </span>
        </s-table>
      </div>
    </a-card>
    <!-- 设置工资条项目 -->
    <a-modal
      title="设置工资条项目"
      :visible="paysipVisible"
      @cancel="paysipVisible = false"
      :footer="null"
      :width="680"
      :bodyStyle="{ 'max-height': '70vh', 'overflow-y': 'auto', padding: '24px' }"
    >
      <div style="font-size: 14px; color: #666">
        <div>
          1）“上课绩效工资”会根据给老师设置的上课绩效工资规则自动计算。关闭后，你可以手动添加一列，结算工资时自行输入金额。
        </div>
        <div>2）编辑工资条项目，只会影响后续老师结算工资的项目名称，不影响之前已创建的工资。</div>
      </div>
      <div class="table-box">
        <div class="table-title">默认项目</div>
        <a-table
          :columns="defaultColumns"
          :data-source="defaultData"
          :pagination="false"
          class="user_management_table"
          style="border: 1px solid #e8e8e8"
        >
          <span slot="action" slot-scope="text, record">
            <span v-if="record.action">
              <a-switch @click="JXchange" v-model="checked" />
            </span>
            <span v-else style="color: rgb(153, 153, 153)">不可操作</span>
          </span>
        </a-table>
      </div>
      <div class="table-box">
        <div class="table-title">自定义项目</div>
        <a-table
          :columns="customColumns"
          :data-source="customData"
          :pagination="false"
          class="user_management_table"
          style="border: 1px solid #e8e8e8"
        >
          <span slot="sort" slot-scope="text, record">
            <span>{{ record.sort }}</span>
          </span>
          <span slot="type" slot-scope="text, record">
            <span> {{ record.type == 1 ? '加钱' : '扣钱' }}</span>
          </span>
          <span slot="name" slot-scope="text, record">
            <span>{{ record.name }}</span>
          </span>
          
          <span slot="action" slot-scope="text, record">
            <a-popconfirm
              title="你确定要删除这项工资吗？"
              ok-text="删除"
              cancel-text="取消"
              @confirm="delPay(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>

            <!-- <span> </span> -->
          </span>
        </a-table>
        <div class="add-item-btn" @click="addpay">
          <span style="margin-right: 5px"><a-icon type="plus" /></span>
          <span>添加工资条项目</span>
        </div>
      </div>
    </a-modal>
    <!-- 添加工资条项目 -->
    <a-modal
      title="添加工资条项目"
      :visible="visiblePay"
      :confirm-loading="confirmLoadingPay"
      @ok="handleOkPay"
      @cancel="visiblePay = false"
    >
      <div class="form-box">
        <span style="margin-right: 5px">工资条类型：</span>
        <div>
          <a-radio-group v-model="payslipForm.type" style="display: flex">
            <a-radio-button :value="1"> 加钱 </a-radio-button>
            <a-radio-button :value="2"> 扣钱 </a-radio-button>
          </a-radio-group>
        </div>
      </div>
      <div class="form-box" style="margin-top: 20px">
        <span style="margin-right: 5px">工资条项目名称：</span>
        <div>
          <a-input placeholder="请输入名称" v-model="payslipForm.name" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import {
  payslipList,
  payslipItems,
  achievementSetting,
  achievementGetSetting,
  addPayslipItems,
  delPayslipItems,
  deleteSettlements,
  exportSettlements,
} from '@/api/wageSettlement'
import CountDown from '@/components/CountDown/CountDown.vue'
export default {
  components: { STable, CountDown },
  data() {
    return {
      keywords: '',
      queryParam: {
        status: undefined,
        school_id: this.$store.state.user.school,
        pay_date: undefined,
      },
      arr: ['name', 'section'],
      columns: [
        {
          title: '结算名称',
          // dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
          width: 200,
          // customRender:(value,row)=>{
          //   console.log(value,1)
          //   return row
          // }
        },
        {
          title: '结算区间',
          // dataIndex: 'name',
          width: 200,
          scopedSlots: { customRender: 'section' },
        },
        {
          title: '结算对象',
          // dataIndex: 'name',
          width: 200,
          scopedSlots: { customRender: 'teacher_user' },
        },
        {
          title: '结算金额',
          // dataIndex: 'name',
          width: 200,
          scopedSlots: { customRender: 'money' },
        },
        {
          title: '发薪日期',
          dataIndex: 'pay_date',
          width: 200,
          // scopedSlots: { customRender: 'name' }
        },
        {
          title: '操作人',
          dataIndex: 'user_name',
          width: 200,
          // scopedSlots: { customRender: 'name' }
        },
        {
          title: '状态',
          // dataIndex: 'user_name',
          width: 200,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          width: 200,
          scopedSlots: { customRender: 'action' },
        },
      ],
      pagination: {
        showTotal: (total) => `共${total}条数据`,
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return payslipList(Object.assign(parameter, this.queryParam, { name: this.keywords })).then((res) => {
          // this.pageNo = Number(parameter.pageNo)
          return res
        })
      },
      paysipVisible: false,
      defaultData: [
        {
          id: 1,
          type_name: '加钱',
          project: '基本工资',
          action: false,
        },
        {
          id: 2,
          type_name: '加钱',
          project: '奖金',
          action: false,
        },
        {
          id: 3,
          type_name: '加钱',
          project: '上课绩效工资',
          action: true,
        },
      ],
      defaultColumns: [
        {
          title: '排序',
          dataIndex: 'id',
          width: 122,
        },
        {
          title: '类型',
          dataIndex: 'type_name',
          width: 122,
        },
        {
          title: '工资条项目',
          dataIndex: 'project',
          width: 280,
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          width: 100,
        },
      ],
      checked: false, //上课绩效工资是否开启
      customData: [],
      customColumns: [
        {
          title: '排序',
          dataIndex: 'sort',
          scopedSlots: { customRender: 'sort' },
          width: 122,
        },
        {
          title: '类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' },
          width: 200,
        },
        {
          title: '工资条项目',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
          width: 200,
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          width: 100,
        },
      ],
      payslipForm: {
        type: 1,
        name: '',
        school_id: this.$store.state.user.school,
      },
      visiblePay: false,
      confirmLoadingPay: false,
    }
  },
  watch: {
    queryParam: {
      handler() {
        this.$refs.table.refresh()
      },
      // immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: false,
      deep: true, // 开启深度监听，默认是false
    },
  },
  methods: {
    monthChange(e, s) {
      // console.log(e, s)
      this.queryParam.pay_date = s
      this.$refs.table.refresh(true)
    },
    getpPayslipItems() {
      payslipItems({ school_id: this.$store.state.user.school, pageSize: 999 })
        .then((res) => {
          this.customData = res.data
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
    },
    openGZT() {
      this.getpPayslipItems()
      achievementGetSetting({
        school_id: this.$store.state.user.school,
        key: 'achievement',
      })
        .then((res) => {
          if (res.value) {
            this.checked = res.value.is_enable
          }
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
      this.paysipVisible = true
    },
    JXchange(e) {
      achievementSetting({
        school_id: this.$store.state.user.school,
        key: 'achievement',
        value: {
          is_enable: e,
        },
      })
        .then((res) => {
          this.$message.success('修改成功')
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
    },
    delPay(id) {
      delPayslipItems(id)
        .then((res) => {
          this.$message.success('删除成功')
          this.getpPayslipItems()
        })
        .catch((err) => {
          this.$message.error(err.data.message || '删除失败')
        })
    },
    addpay() {
      this.visiblePay = true
    },
    handleOkPay() {
      this.confirmLoadingPay = true
      addPayslipItems(this.payslipForm)
        .then((res) => {
          this.visiblePay = false
          this.payslipForm.type = 1
          this.payslipForm.name = ''
          this.getpPayslipItems()
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
        .finally(() => {
          this.confirmLoadingPay = false
        })
    },
    goAdd() {
      let type = 1
      this.$router.push({
        // path:`/finance/wageSettlementExpand/add_settlement/${type}`,
        name: 'add_settlement',
        params: {
          type,
        },
      })
    },
    goInfo(id) {
      this.$router.push({
        name: 'payslip_info',
        params: {
          id,
        },
      })
    },
    goSet() {
      this.$router.push({
        name: 'set_wage',
      })
    },
    exportItem(id) {
      exportSettlements(id, { school_id: this.$store.state.user.school })
        .then((res) => {
          this.$message.success('导出成功')
          window.location.href = res.url.url + res.url.path
        })
        .catch((err) => {
          this.$message.error(err.data.message || '导出失败')
        })
    },
    deleteItem(id) {
      let that = this
      this.$confirm({
        title: '删除结算记录',
        content: (h) => <div>你确定要删除此记录吗？</div>,
        onOk() {
          deleteSettlements(id)
            .then((res) => {
              that.$message.success('删除成功')
              that.$refs.table.refresh()
            })
            .catch((err) => {
              that.$message.error(err.data.message || '删除失败')
            })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test',
      })
    },
  },
}
</script>

<style lang="less" scoped>
.btn-list {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.mr10 {
  margin-right: 10px;
}
.table-box {
  margin-top: 16px;
  .table-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 9px;
  }
}
.add-item-btn {
  text-align: center;
  border: 1px solid #e8e8e8;
  border-top: 0;
  height: 50px;
  line-height: 50px;
  cursor: pointer;
  span {
    color: #666;
  }
  &:hover span {
    color: #1890ff;
  }
}
.form-box {
  display: flex;
  align-items: center;
}
</style>